//
//  SSWBComposeTypeView.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/1/31.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit
import pop

/// 撰写微博类型视图
class SSWBComposeTypeView: UIView {
    
    // MARK: - 私有属性
    
    /// 返回按钮
    @IBOutlet weak var backButton: UIButton!
    
    /// 返回按钮的X约束
    @IBOutlet weak var backButtonCenterXConstraint: NSLayoutConstraint!
    
    /// 关闭按钮的X约束
    @IBOutlet weak var closeButtonCenterXConstraint: NSLayoutConstraint!
    
    /// 滚动视图
    @IBOutlet weak var scrollView: UIScrollView!
    
    /// 底部工具按钮的移动距离
    fileprivate var buttonMoveMargin: CGFloat {
        return scrollView.bounds.width / 6
    }
    
    let animationDuration: TimeInterval = 0.5
    
    /// 按钮数组
    fileprivate let buttonsInfo: [[String: String]] = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "SSWBComposeViewController"],
                                                       ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                                                       ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                                                       ["imageName": "tabbar_compose_lbs", "title": "签到"],
                                                       ["imageName": "tabbar_compose_review", "title": "点评"],
                                                       ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "moreButtonClick"],
                                                       ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                                                       ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                                                       ["imageName": "tabbar_compose_music", "title": "音乐"],
                                                       ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
    ]
    
    /// 完成回调
    fileprivate var completionBlock: ((_ clsName: String?) -> ())?
    
    /// 实例化方法
    ///
    /// - Returns: SSWBComposeTypeView
    class func composeTypeView() -> SSWBComposeTypeView {
        
        let nib = UINib(nibName: "SSWBComposeTypeView", bundle: nil).instantiate(withOwner: nil, options: nil).first as? SSWBComposeTypeView
        
        // xib加载默认是600 * 600
        nib?.frame = UIScreen.main.bounds
        nib?.setupUI()
        return nib ?? SSWBComposeTypeView()
    }
    
    /// 显示当前视图
    func show(completion: @escaping (_ clsName: String?) -> ()) {
        
        // 记录闭包
        completionBlock = completion
        
        // 1.将当前视图添加到main的view上
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        
        // 2.添加视图
        vc.view.addSubview(self)
        
        // 3.显示动画
        showCurrentView()
        
    }
    
    // MARK: - 监听方法
    @objc fileprivate func clickButton(selectedButton: SSWBComposeTypeButton) {
        
        print("点我了\(selectedButton.clsName)")
        
        // 1.判断当前显示的视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 2.遍历当前视图
        // - 被选中的按钮放大
        // - 其他按钮缩小
        for (i, btn) in scrollView.subviews[page].subviews.enumerated() {
            
            // 1.缩放动画
            let scale = btn == selectedButton ? 1.5 : 0.2
            let scaleAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            
            // x,y表示坐标,需要用NSValue包装
            scaleAnimation?.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnimation?.duration = animationDuration
            
            // 2.渐变动画
            let alphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnimation?.fromValue = 1
            alphaAnimation?.toValue = 0.2
            alphaAnimation?.duration = animationDuration
            
            // 3.添加多个动画 - 动画组概念
            btn.pop_add(scaleAnimation, forKey: nil)
            btn.pop_add(alphaAnimation, forKey: nil)
            
            // 4.监听动画完成
            if i == 0 {
                alphaAnimation?.completionBlock = {(_, _) in
                    self.completionBlock?(selectedButton.clsName)
                }
            }
        }
    }
    
    /// scrollView滚动到第二页
    @objc fileprivate func moreButtonClick() {
        // 1.滚动
        UIView.animate(withDuration: animationDuration) {
            self.scrollView.contentOffset = CGPoint(x: self.scrollView.bounds.width, y: 0)
        }
        
        // 2.处理底部按钮 - 让两个按钮分开
        backButton.isHidden = false
        
        backButtonCenterXConstraint.constant -= buttonMoveMargin
        closeButtonCenterXConstraint.constant += buttonMoveMargin
        
        UIView.animate(withDuration: animationDuration) {
            self.backButton.alpha = 1
            self.layoutIfNeeded()
        }
    }
    
    /// 关闭视图
    @IBAction func close() {
        hideButton()
    }
    
    /// scrollView滚动到第一页
    @IBAction func back() {
        // 1.滚动
        UIView.animate(withDuration: animationDuration) {
            self.scrollView.contentOffset = CGPoint(x: 0, y: 0)
        }
        // 2.处理底部按钮 - 隐藏back按钮,关闭按钮的位置移动到center
        
        backButtonCenterXConstraint.constant += buttonMoveMargin
        closeButtonCenterXConstraint.constant -= buttonMoveMargin
        
        UIView.animate(withDuration: animationDuration, animations: {
            self.backButton.alpha = 0
            self.layoutIfNeeded()
        }) { (_) in
            self.backButton.isHidden = true
        }
    }
}


// MARK: - 动画方法扩展
fileprivate extension SSWBComposeTypeView {
    
    // MARK: - 消失动画部分
    
    /// 隐藏按钮动画
    func hideButton() {
        
        // 1.根据contenOffset判断当前是第几页
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        // 2.遍历v中的所有的按钮
        for (i,button) in v.subviews.enumerated().reversed() {
            
            // 创建动画
            let animation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            // 设置动画
            animation?.fromValue = button.center.y
            animation?.toValue = button.center.y + 400
            animation?.springBounciness = 6
            animation?.springSpeed = 6
            animation?.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            
            // 添加动画
            button.layer.pop_add(animation, forKey: nil)
            
            // 动画结束后的闭包 - 隐藏当前视图,第0个按钮的动画是最后一个执行的
            if i == 0 {
                animation?.completionBlock = {(_, _) in
                    self.hideCurrentView()
                }
            }
        }
    }
    
    func hideCurrentView() {
        
        // 1.创建动画
        let animation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        // 2.设置动画
        
        animation.fromValue = 1
        animation.toValue = 0
        animation.duration = animationDuration
        
        animation.completionBlock = {(_, _) in
            self.removeFromSuperview()
        }
        
        // 3.添加到视图执行动画
        pop_add(animation, forKey: nil)
    }
    
    // MARK: - 显示动画部分
    
    /// 动画显示当前视图
    func showCurrentView() {
        
        // 1.创建动画
        let animation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        animation.fromValue = 0
        animation.toValue = 1
        animation.duration = animationDuration
        
        // 2.添加到视图
        pop_add(animation, forKey: nil)
        
        // 3.添加按钮的动画
        showButtons()
    }
    
    /// 弹力显示所有的按钮
    func showButtons() {
        
        // 1.获取scrollView子视图的第0个视图
        let v = scrollView.subviews[0]
        
        // 2.遍历v的所有按钮
        for (i, button) in v.subviews.enumerated() {
            
            // 创建动画
            let animation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            // 设置动画
            animation?.fromValue = button.center.y + 400
            animation?.toValue = button.center.y
            animation?.springBounciness = 6
            animation?.springSpeed = 6
            
            // 设置动画启动时间
            animation?.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            
            button.layer.pop_add(animation, forKey: nil)
        }
    }
    
}

// MARK: - private会让extension所有的方法都是私有
fileprivate extension SSWBComposeTypeView {
    
    func setupUI() {
        
        // 1.强行更新布局
        layoutIfNeeded()
        
        // 2.向scrollView添加视图
        let frame = scrollView.bounds
        
        let width = scrollView.bounds.width
        
        for i in 0 ..< 2 {
            
            let v = UIView(frame: frame.offsetBy(dx: CGFloat(i) * width, dy: 0))
            // 3.向视图添加按钮
            addButtons(v: v, idx: i * 6)
            // 4.将视图添加到scrollView
            scrollView.addSubview(v)
        }
        
        // 5.设置scrollView
        scrollView.contentSize = CGSize(width: 2 * width, height: 0)
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isScrollEnabled = false
    }
    
    /// 向V中添加按钮,按钮的数组索引从idx开始
    ///
    /// - Parameters:
    ///   - v: 视图对象
    ///   - idx: 索引
    func addButtons(v: UIView, idx: Int) {
        
        // 从idx开始,添加6个按钮
        let count = 6
        
        for i in idx ..< idx + count {
            
            if i >= buttonsInfo.count {
                break
            }
            
            // 1.从数组字典中获取图像名称和文字
            guard let imageName = buttonsInfo[i]["imageName"], let title = buttonsInfo[i]["title"] else {
                continue
            }
            
            // 2.创建按钮
            let button = SSWBComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            
            // 3.添加监听方法 - Selector(字符串)
            if let actionName = buttonsInfo[i]["actionName"] {
                button.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                button.addTarget(self, action: #selector(clickButton(selectedButton:)), for: .touchUpInside)
            }
            
            // 4.要展现的类名 - 不需要判断守护
            button.clsName = buttonsInfo[i]["clsName"]
            
            // 5.将button添加到视图
            v.addSubview(button)
            
        }
        
        // 布局按钮
        
        // 准备常量
        let buttonSize = CGSize(width: 100, height: 100)
        let margin: CGFloat = (v.bounds.width - 3 * buttonSize.width) / 4
        
        // 遍历视图的子视图
        for (i,button) in v.subviews.enumerated() {
            
            let y: CGFloat = i > 2 ? v.bounds.height - buttonSize.height : 0
            
            let col = i % 3
            
            let x = CGFloat(col + 1) * margin + buttonSize.width * CGFloat(col)
            
            button.frame = CGRect(x: x, y: y, width: buttonSize.width, height: buttonSize.height)
            
        }
    }
}
